package auth

import (
	"context"
	"fast-boot/app/api/wxapp/internal/svc"
	"fast-boot/app/api/wxapp/internal/types"
	"fast-boot/app/model"
	"fast-boot/common/cachex"
	"fast-boot/common/globalkey"
	"fast-boot/common/xerr"
	"fmt"
	"github.com/hwUltra/fb-tools/jwtx"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type CodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) CodeLogic {
	return CodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CodeLogic) Code(req types.AuthCodeReq) (resp *types.TokenResp, err error) {
	fmt.Println(l.svcCtx.Config.Sms.Template["Login"])
	code2Session, err := l.svcCtx.WxMiniApp.Code2Session(req.Code)
	if err != nil {
		return nil, xerr.NewErrMsg("code2Session 解码错误:" + err.Error())
	}
	key := fmt.Sprintf(globalkey.CacheWxAppSessionKey, code2Session.OpenID)

	c := cachex.NewStore(l.svcCtx.Config.Cache)
	if err := c.Cache.SetWithExpire(key, code2Session.SessionKey, 48*time.Minute); err != nil {
		return nil, err
	}
	item := model.UserThirdModel{}
	if err := l.svcCtx.GormClient.GormDb.Where("platform = 'wxapp' and openid = ?", code2Session.OpenID).First(&item).Error; err != nil {
		return nil, err
	}
	token := ""
	if item.Id == 0 {
		//没有数据插入数据
		item.Openid = code2Session.OpenID
		item.Platform = "wxapp"
		l.svcCtx.GormClient.GormDb.Create(&item)
	} else {
		if item.Uid > 0 {
			now := time.Now().Unix()
			accessExpire := l.svcCtx.Config.Auth.AccessExpire
			token, _ = jwtx.NewJwtX(l.ctx, l.svcCtx.Config.JwtUserKey).GetToken(l.svcCtx.Config.Auth.AccessSecret, now, accessExpire, item.Uid)
		}
	}

	return &types.TokenResp{
		OpenID: code2Session.OpenID,
		Token:  token,
	}, nil

}
